# -*- coding: utf-8 -*-

"""pyqtgraph 与 pyside6 的 多线程 动态绘图示例代码"""

from PySide6 import QtWidgets, QtCore
import pyqtgraph as pg
import numpy as np


# 创建一个后台工作线程
class WorkerThread(QtCore.QThread):
    # 定义一个信号，用于发送数据（使用 object 类型以支持多种数据类型）
    data_signal = QtCore.Signal(object)

    def __init__(self, parent=None):
        super(WorkerThread, self).__init__(parent)
        self.is_running = True

    def run(self):
        while self.is_running:
            # 生成随机数据
            data = np.random.normal(size=(100,))
            # 发送数据
            self.data_signal.emit(data)
            # 休眠一段时间
            QtCore.QThread.msleep(100)

    def stop(self):
        self.is_running = False

    # 创建主窗口


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('PyQtGraph MultiThread Example')

        # 创建图形小部件
        self.graphicsLayoutWidget = pg.GraphicsLayoutWidget(self)
        self.setCentralWidget(self.graphicsLayoutWidget)

        # 创建一个绘图区域并添加一条曲线
        self.plot = self.graphicsLayoutWidget.addPlot()
        self.curve = pg.PlotDataItem()
        self.plot.addItem(self.curve)

        # 实例化线程
        self.worker_thread = WorkerThread()

        # 连接信号槽，处理线程发出的数据
        self.worker_thread.data_signal.connect(self.update_plot)

        # 启动线程
        self.worker_thread.start()

    def update_plot(self, data):
        # 更新曲线数据
        self.curve.setData(y=data)

    def closeEvent(self, event):
        # 停止线程
        self.worker_thread.stop()
        # 等待线程结束
        self.worker_thread.wait()
        # 调用基类的closeEvent
        super(MainWindow, self).closeEvent(event)


if __name__ == '__main__':
    # 创建应用和主窗口
    app = QtWidgets.QApplication([])
    win = MainWindow()
    win.showMaximized()

    # 进入程序主循环
    app.exec()